package com.quyunshuo.module.home.fragment.compose

import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.manager.AppUsage

@Composable
fun HomePage(appUsages: List<AppUsage>) {

    Box(Modifier.fillMaxSize()) {
        LazyColumn {
            items(appUsages) {
                AppUsageItem(it)
            }
        }
    }

}

@Composable
fun AppUsageItem(appUsage: AppUsage) {
    // 将 Drawable 转换为 Bitmap
    appUsage.icon?.apply {
        val bitmap = remember(appUsage.icon) {
            val bitmap = Bitmap.createBitmap(
                appUsage.icon.intrinsicWidth.coerceAtLeast(1),
                appUsage.icon.intrinsicHeight.coerceAtLeast(1),
                Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            appUsage.icon.setBounds(0, 0, canvas.width, canvas.height)
            appUsage.icon.draw(canvas)
            bitmap
        }

        Row(Modifier
            .fillMaxWidth()
            .height(50.dp)) {
            Image(painter = BitmapPainter(bitmap.asImageBitmap()), contentDescription = null)
            Text(appUsage.appName, color = Color.White)
            Text(appUsage.formattedDuration(), color = Color.White)
        }
    }

}

@Composable
@Preview
fun HomePagePreview() {
    HomePage(
        listOf(
            AppUsage("asdf", ":asdf", R.drawable.setting_icon.toDrawable(), 0L, 0L),
            AppUsage("asdf", ":asdf", R.drawable.setting_icon.toDrawable(), 0L, 0L)

        )
    )
}